<?php
namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT);

use app\admin\Controller;
use HttpException;
use think\Config;
use think\Db;
use think\Loader;
use think\Request;

class ActZdpigyearPrize extends Controller
{
    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];

    protected static $isdelete = false;

    protected function filter(&$map)
    {
        if ($this->request->param("name")) {
            $map['name'] = ["like", "%" . $this->request->param("name") . "%"];
        }
        if ($this->request->param("city")) {
            $map['city'] = ["like", "%" . $this->request->param("city") . "%"];
        }
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        $model = model('ActZdpigyearPrize');

        // 列表过滤器，生成查询Map对象
        $map = $this->search($model, [$this->fieldIsDelete => $this::$isdelete]);

        // 特殊过滤器，后缀是方法名的
        $actionFilter = 'filter' . $this->request->action();
        if (method_exists($this, $actionFilter)) {
            $this->$actionFilter($map);
        }

        // 自定义过滤器
        if (method_exists($this, 'filter')) {
            $this->filter($map);
        }
        $map['_order_by']='weight desc';
        $this->datalist($model, $map);

        $list=model('ZdPrizeInventedCode')->distinct('prize_type')->field('prize_type,name')->select();
        $this->view->assign('name_list',$list);
        return $this->view->fetch();
    }


    /**
     * 添加
     * @return mixed
     */
    public function add()
    {
        $controller = $this->request->controller();

        if ($this->request->isAjax()) {
            // 插入
            $data = $this->request->except(['id']);

            // 验证
            if (class_exists($validateClass = Loader::parseClass(Config::get('app.validate_path'), 'validate', $controller))) {
                $validate = new $validateClass();
                if (!$validate->check($data)) {
                    return ajax_return_adv_error($validate->getError());
                }
            }

            // 写入数据
            if (
                class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $this->parseCamelCase($controller)))
                || class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $controller))
            ) {
                //使用模型写入，可以在模型中定义更高级的操作
                $model = model('ActZdpigyearPrize');
                $ret = $model->isUpdate(false)->save($data);
            } else {
                // 简单的直接使用db写入
                Db::startTrans();
                try {
                    $model = model('ActZdpigyearPrize');
                    $ret = $model->insert($data);
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();

                    return ajax_return_adv_error($e->getMessage());
                }
            }

            return ajax_return_adv('添加成功');
        } else {
            // 添加
            $list=model('ZdPrizeInventedCode')->distinct('prize_type')->field('prize_type,name')->select();
            $this->view->assign('name_list',$list);
            return $this->view->fetch(isset($this->template) ? $this->template : 'edit');
        }
    }

    /**
     * 编辑
     * @return mixed
     */
    public function edit()
    {
        $controller = $this->request->controller();

        if ($this->request->isAjax()) {
            // 更新
            $data = $this->request->post();
            if (!$data['id']) {
                return ajax_return_adv_error("缺少参数ID");
            }

            // 验证
            if (class_exists($validateClass = Loader::parseClass(Config::get('app.validate_path'), 'validate', $controller))) {
                $validate = new $validateClass();
                if (!$validate->check($data)) {
                    return ajax_return_adv_error($validate->getError());
                }
            }

            // 更新数据
            if (
                class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $this->parseCamelCase($controller)))
                || class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $controller))
            ) {
                // 使用模型更新，可以在模型中定义更高级的操作
                $model = model('ActZdpigyearPrize');
                $ret = $model->isUpdate(true)->save($data, ['id' => $data['id']]);
            } else {
                // 简单的直接使用db更新
                Db::startTrans();
                try {
                    $model = model('ActZdpigyearPrize');
                    $ret = $model->where('id', $data['id'])->update($data);
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();

                    return ajax_return_adv_error($e->getMessage());
                }
            }

            return ajax_return_adv("编辑成功");
        } else {
            // 编辑
            $id = $this->request->param('id');
            if (!$id) {
                throw new HttpException(404, "缺少参数ID");
            }
            $vo = $model = model('ActZdpigyearPrize')->find($id);
            if (!$vo) {
                throw new HttpException(404, '该记录不存在');
            }

            $this->view->assign("vo", $vo);
            $list=model('ZdPrizeInventedCode')->distinct('prize_type')->field('prize_type,name')->select();
            $this->view->assign('name_list',$list);
            return $this->view->fetch();


        }
    }

    /**
     * 永久删除
     */
    public function deleteForever()
    {
        $model = model('ActZdpigyearPrize');
        $pk = $model->getPk();
        $ids = $this->request->param($pk);
        $where[$pk] = ["in", $ids];
        if (false === $model->where($where)->delete()) {
            return ajax_return_adv_error($model->getError());
        }

        return ajax_return_adv("删除成功");
    }


    // 文件上传预留
    public function upload()
    {
        // 获取上传文件
        $file = request() -> file('image');
        if($file) {
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if ($info) {
                // $info->getExtension();         // 文件扩展名
                // 获取得到图片的绝对路径 => E:\xampp1\htdocs\WX_SMALL\public\uploads\20181116\*.jpg
                $mes = $info->getSaveName();     // 文件名相对路径
                $mes = str_replace('\\','/',$mes);
                $domain = Request::instance()->domain();
                $domain = str_replace('http', 'https', $domain);
                $mes = $domain .'/WX_SMALL/public/uploads/'. $mes;
                return $mes;
            } else {
                // 文件上传失败后的错误信息
                $mes = $file->getError();
                return ajax_return_adv_error($mes);
            }
        }else{
            return ajax_return_adv_error('文件不存在');
        }
    }

    // 文件上传预留
    public function uploadpdf()
    {
        // 获取上传文件
        $file = request() -> file('pdf_upload');
        if($file) {
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads'.DS.'pdf');
            if ($info) {
                // $info->getExtension();         // 文件扩展名
                // 获取得到图片的绝对路径 => E:\xampp1\htdocs\WX_SMALL\public\uploads\20181116\*.jpg
                $mes = $info->getSaveName();     // 文件名相对路径
                $mes = str_replace('\\','/',$mes);
                $domain = Request::instance()->domain();
                $domain = str_replace('http', 'https', $domain);
                $mes = $domain .'/WX_SMALL/public/uploads/pdf/'. $mes;
                return $mes;
            } else {
                // 文件上传失败后的错误信息
                $mes = $file->getError();
                return ajax_return_adv_error($mes);
            }
        }else{
            return ajax_return_adv_error('文件不存在');
        }
    }

}
